using System;
using System.IO;
using System.Web.UI;
using ViewStateHandlers;

namespace Rioshu.Web.ViewStateHandlers
{
    public class TinyPagePersister : IViewStateHandlersPersister
    {
        public TinyPagePersister()
        {
            Configuration = TinyPagePersisterConfigurationHandler.GetConfiguration();
            Compressor = CompressorFactory.CreateCompressor(Configuration.CompressionType);
        }

        public IStringCompressor Compressor { get; set; }
        public TinyPagePersisterConfigurationHandler Configuration { get; set; }

        #region IViewStateHandlersPersister Members

        public void SaveState(Page page, Pair pageState)
        {
            var formatter = new LosFormatter();
            using (var sw = new StringWriter()) {
                formatter.Serialize(sw, pageState);
                var vstate = Compressor.Compress(sw.ToString());
                page.ClientScript.RegisterHiddenField(Configuration.FieldName, vstate);
            }
        }

        public Pair LoadState(Page page)
        {
            var vstate = page.Request.Form[Configuration.FieldName];
            if (string.IsNullOrEmpty(vstate))
                throw new InvalidOperationException("There is not a Compressed Client ViewState on page");
            vstate = Compressor.Decompress(vstate);
            
            var formatter = new LosFormatter();
            var pair = formatter.Deserialize(vstate) as Pair;

            return pair;
        }

        #endregion
    }
}